package com.alks.function.service.impl.produce;

import com.alks.common.aop.AutoPageAop;
import com.alks.common.aop.RedisLock;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.service.RedisService;
import com.alks.common.utils.UserInfoUtil;
import com.alks.common.utils.beanutils.ObjectUtils;
import com.alks.common.utils.stringUtils.ZStringUtils;
import com.alks.entity.data.entity.*;
import com.alks.entity.data.entity.dispatch.*;
import com.alks.entity.data.entity.imes.StyleInfo;
import com.alks.entity.data.page.PageRecord;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.chengKong.produce.PcLotDetailDto;
import com.alks.function.data.dto.produce.*;
import com.alks.function.data.request.chengKong.LotNoToStyleRequest;
import com.alks.function.data.request.produce.deleteRequest;
import com.alks.function.data.request.produce.dispatchHeadRequest;
import com.alks.function.data.request.produce.doDispatchRequest;
import com.alks.function.mapper.SdCompanyMapper;
import com.alks.function.mapper.administration.PcEmployeeMapper;
import com.alks.function.mapper.chengKong.PcLotHeadMapper;
import com.alks.function.mapper.produce.CutPlanMapper;
import com.alks.function.mapper.produce.CuttingDispatchHeadMapper;
import com.alks.function.service.produce.CuttingDispatchHeadService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CuttingDispatchHeadServiceImpl implements CuttingDispatchHeadService {

    @Autowired
    private CuttingDispatchHeadMapper cuttingDispatchHeadMapper;

    @Autowired
    private PcEmployeeMapper pcEmployeeMapper;

    @Autowired
    private PcLotHeadMapper pcLotHeadMapper;

    @Autowired
    private SdCompanyMapper sdCompanyMapper;

    /**
     * 冲裁派工查询
     *
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo dispatchHeadList(dispatchHeadRequest request) {
        PageRecord<PcCuttingDispatchHeadDto> list = new PageRecord<>();
        UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
        request.setCompanyId(userInfo.getCompanyId());
        if (!ObjectUtils.isEmpty(request.getUserId())) {
            request.setUserId(userInfo.getLoginName());
        }
        List<PcCuttingDispatchHeadDto> headList = cuttingDispatchHeadMapper.getCuttingDispatchHeadList(request);
        PageInfo pageInfo = new PageInfo(headList);
        list.setList(headList);
        list.setTotal(pageInfo.getTotal());
        return ResponseInfo.ok(list);
    }

    /**
     * 派工号码明细
     *
     * @param request
     * @return
     */
    @Override
    public ResponseInfo dispatchDetailList(dispatchHeadRequest request) {
        List<dispatchDetailDto> list = cuttingDispatchHeadMapper.getCuttingDispatchDetailList(request);
        return ResponseInfo.ok(list);
    }

    /**
     * 插入冲裁资料-选择指令查询
     *
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo loadCuttingCheckerList(LotNoToStyleRequest request) {
        PageRecord<CutDispatchLotDto> list = new PageRecord<>();
        String companyId = UserInfoUtil.getUserInfo().getCompanyId();
        List<CutDispatchLotDto> canDispatchLotNoList = cuttingDispatchHeadMapper.getCanDispatchLotNoList(companyId, request);
        PageInfo pageInfo = new PageInfo(canDispatchLotNoList);
        list.setList(canDispatchLotNoList);
        list.setTotal(pageInfo.getTotal());
        return ResponseInfo.ok(list);
    }

    /**
     * 插入冲裁资料-冲裁派工查询
     *
     * @param lotNo
     * @param lsNos
     * @return
     */
    @Override
    public ResponseInfo loadCutLabelTree(String lotNo, List<String> lsNos) {
        List<LabelPartNameDto> list = null;
        String companyId = UserInfoUtil.getUserInfo().getCompanyId();
        CutDispatchLotDto canDispatchLotNo = cuttingDispatchHeadMapper.getCanDispatchLotNo(companyId, lotNo);
        if (ObjectUtils.isEmpty(lsNos)) {
            throw new ServiceErrorException("轮次不能为空!");
        }
        if (ObjectUtils.isEmpty(canDispatchLotNo)) {
            throw new ServiceErrorException("无效的指令信息");
        } else {
            int diffNum;
            if ("Y".equals(canDispatchLotNo.getCombineLot())) {
                list = cuttingDispatchHeadMapper.selectUnDispatchCombineLabel(canDispatchLotNo.getCompanyId(), lotNo, lsNos);
                diffNum = this.cuttingDispatchHeadMapper.selectSizeQtyChangeNumCombine(lotNo);
            } else {
                list = cuttingDispatchHeadMapper.selectUnDispatchLabel(canDispatchLotNo.getCompanyId(), lotNo, lsNos);
                diffNum = this.cuttingDispatchHeadMapper.selectSizeQtyChangeNum(lotNo);
            }
            if (diffNum > 0) {
                throw new ServiceErrorException("存在指令尺码数量发生变化,请联系成控批次处理!");
            } else {
                List<CuttingDispatchTreeData> result = new ArrayList();
                if (ObjectUtils.isEmpty(list)) {
                    return ResponseInfo.ok(result);
                } else {
                    Map<String, CuttingDispatchTreeData> partMap = new LinkedHashMap();
                    Map<String, CuttingDispatchTreeData> partLotMap = new LinkedHashMap();
                    Map<String, CuttingDispatchTreeData> partLotSizeMap = new LinkedHashMap();
                    Iterator var10 = list.iterator();
                    while (var10.hasNext()) {
                        LabelPartNameDto crl = (LabelPartNameDto) var10.next();
                        CuttingDispatchTreeData partData = (CuttingDispatchTreeData) partMap.get(crl.getPartName());
                        if (ObjectUtils.isEmpty(partData)) {
                            partData = new CuttingDispatchTreeData();
                            partData.setTitle(crl.getPartName());
                            partData.setCutBatch(String.valueOf(crl.getCutSeq()));
                            partData.setMtlOrderQty(crl.getMtlName());
                            partData.setLeaf(false);
                            partData.setType("part");
                            partMap.put(crl.getPartName(), partData);
                            result.add(partData);
                        }
                        String partLotKey = crl.getPartName() + crl.getLotNo();
                        CuttingDispatchTreeData partLotData = (CuttingDispatchTreeData) partLotMap.get(partLotKey);
                        if (ObjectUtils.isEmpty(partLotData)) {
                            partLotData = new CuttingDispatchTreeData();
                            partLotData.setTitle(crl.getLotNo());
                            partLotData.setCutBatch("-");
                            partLotData.setRemainQty("-");
                            partLotData.setRealQty("-");
                            partLotData.setMtlOrderQty("-");
                            partLotData.setLeaf(false);
                            partLotData.setType("lot");
                            partData.getChildren().add(partLotData);
                            partLotMap.put(partLotKey, partLotData);
                        }

                        String partLotSizeKey = crl.getPartName() + crl.getLotNo() + crl.getSizeNo();
                        CuttingDispatchTreeData partLotSizeData = (CuttingDispatchTreeData) partLotSizeMap.get(partLotSizeKey);
                        if (ObjectUtils.isEmpty(partLotSizeData)) {
                            partLotSizeData = new CuttingDispatchTreeData();
                            partLotSizeData.setTitle(crl.getSizeNo());
                            partLotSizeData.setCutBatch(crl.getCutSize());
                            partLotSizeData.setRemainQty("0");
                            partLotSizeData.setRealQty("0");
                            partLotSizeData.setMtlOrderQty(String.valueOf(crl.getOrderQty()));
                            partLotSizeData.setLeaf(false);
                            partLotSizeData.setType("size");
                            partLotData.getChildren().add(partLotSizeData);
                            partLotSizeMap.put(partLotSizeKey, partLotSizeData);
                        }

                        CuttingDispatchTreeData labelData = new CuttingDispatchTreeData();
                        labelData.setTitle(crl.getLabelNo());
                        labelData.setCutBatch(crl.getBatchCode());
                        labelData.setRemainQty(String.valueOf(crl.getCutNum()));
                        labelData.setRealQty(String.valueOf(crl.getQty()));
                        labelData.setMtlOrderQty(String.valueOf(crl.getLsNo()));
                        labelData.setLeaf(true);
                        labelData.setType("label");
                        int remainQty = Integer.valueOf(partLotSizeData.getRemainQty()) + Integer.valueOf(crl.getQty());
                        partLotSizeData.setRemainQty(String.valueOf(remainQty));
                        partLotSizeData.getChildren().add(labelData);
                    }
                    return ResponseInfo.ok(result);
                }
            }
        }
    }

    @Override
    @AutoPageAop
    public ResponseInfo searchList(ManulDispatchHead manulDispatchHead) {
        Map<String, Object> map = new HashMap<>();
        manulDispatchHead.setProcessCode("01");
        manulDispatchHead.setCompanyId(UserIdThread.get().getCompanyId());
        List<ManulDispatchHead> list = cuttingDispatchHeadMapper.searchList(manulDispatchHead);
        map.put("list", list);
        map.put("total", new PageInfo(list).getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo dispatchDetailSizeList(ManulDispatchHead manulDispatchHead) {
        List<ManulDispatchDetail> list = cuttingDispatchHeadMapper.dispatchDetailSizeList(manulDispatchHead);
        return ResponseInfo.ok(list);
    }

    @Override
    @Transactional
    public ResponseInfo delete(List<ManulDispatchHead> list) {
        String processCode = "01";
        List<ManulDispatchHead> heads = new ArrayList<>();
        for (ManulDispatchHead manulDispatchHead : list) {
            ManulDispatchHead manageHead = cuttingDispatchHeadMapper.selectByRowids(manulDispatchHead, processCode);
            if (manageHead != null) heads.add(manageHead);
        }
        if (heads.size() != list.size()) {
            return ResponseInfo.error("存在无效的派工信息");
        } else {
            long time = new Date().getTime();
            Iterator var5 = list.iterator();
            while (var5.hasNext()) {
                List<String> strings = List.of("冯长春", "林添发");
                ManulDispatchHead head = (ManulDispatchHead) var5.next();
                String name = UserIdThread.get().getUserName();
                if (time - head.getDispatchDate().getTime() > 60 * 60 * 24 * 1000L) {
                    if (!strings.contains(name))
                        return ResponseInfo.error("隔天记录,不能删除!");
                }
                if (!UserIdThread.get().getUserName().equals(head.getDispatchName())) {
                    if (!strings.contains(name))
                        return ResponseInfo.error("不能删除别人的派工记录!");
                }
                List<DispatchCollection> dc = cuttingDispatchHeadMapper.queryByDispatchNo(head.getDispatchType());
                if (dc != null && dc.size() > 0) {
                    return ResponseInfo.error("派工单已采集,不能删除!");
                }
                CuttingDispatchHead param = new CuttingDispatchHead();
                param.setWorkerName(head.getWorkerName());
                param.setLotNo(head.getLotNo());
                param.setLsNo(head.getLsNo());
                param.setPlanNo(head.getDispatchType());
                param.setPartName(head.getPartName());
                param.setCompanyId(UserIdThread.get().getCompanyId());
                int salaryList = cuttingDispatchHeadMapper.queryByDispatchNoAndPartName(param);
                if (salaryList > 0) {
                    return ResponseInfo.error("派工单已结算,不能删除!");
                }
                cuttingDispatchHeadMapper.insertIntoO(head, UserIdThread.get().getLoginName());
                if (!ZStringUtils.isEmpty(head.getCombineLotNo())) {
                    cuttingDispatchHeadMapper.deleteByDispatchNo(head);
                    cuttingDispatchHeadMapper.deleteByDispatchHeadNo(head);
                } else {
                    cuttingDispatchHeadMapper.deleteByHead(head);
                }
            }
            cuttingDispatchHeadMapper.deleteByRowids(list, processCode);
        }
        return ResponseInfo.ok();
    }

    private String prefix = "html";


    @Override
    public ResponseInfo planNoPrint(String dispatchType, HttpServletRequest request) throws IOException {
        Map<String, Object> map = new HashMap<>();
        List<ManulDispatchHead> headList = cuttingDispatchHeadMapper.selectByDispatchType(dispatchType);
        if (ZStringUtils.isEmpty(headList)) {
            return ResponseInfo.error("未找到派工信息");
        }
        ManulDispatchHead firstRecord = headList.get(0);
        Date now = new Date();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        map.put("dispatchType", dispatchType);
        map.put("printDate", sdf1.format(now));
        map.put("dispatchDate", sdf1.format(firstRecord.getDispatchDate()));
        map.put("workerName", firstRecord.getWorkerName());
        map.put("dispatchName", firstRecord.getDispatchName());
        LotHead lotHead = new LotHead();
        lotHead.setLotNo(firstRecord.getLotNo());
        lotHead = this.cuttingDispatchHeadMapper.getLotHead(lotHead);
        if (ZStringUtils.isNull(lotHead)) {
            return ResponseInfo.error("指令不存在");
        }
        if (ZStringUtils.isEmpty(lotHead.getCutNo())) {
            StyleInfo param = new StyleInfo();
            param.setStyleNo(lotHead.getStyle());
            List<StyleType> res = this.cuttingDispatchHeadMapper.selectStyleRemakrByType(param);
            String cutNo = "";
            for (int i = 0; i < res.size(); i++) {
                cutNo = cutNo + ((StyleType) res.get(i)).getCutTool() + "/";
            }
            cutNo = cutNo.substring(0, cutNo.length() - 1);
            lotHead.setCutNo(cutNo);
        }
        map.put("lotHead", lotHead);
        if (ZStringUtils.isNotNull(lotHead.getSurplusQty()) && lotHead.getSurplusQty().intValue() > 0) {
            map.put("orderQtyStr", ZStringUtils.format("{}+{}", new Object[]{lotHead.getOrderQty(), lotHead.getSurplusQty()}));
        } else {
            map.put("orderQtyStr", ZStringUtils.format("{}", new Object[]{lotHead.getOrderQty()}));
        }
        int minLsNo = Integer.MAX_VALUE;
        int maxLsNo = Integer.MIN_VALUE;
        Map<String, List<Integer>> partCountMap = new LinkedHashMap<>();
        for (ManulDispatchHead head : headList) {
            if (minLsNo > head.getLsNo().intValue()) minLsNo = head.getLsNo().intValue();
            if (maxLsNo < head.getLsNo2().intValue()) maxLsNo = head.getLsNo2().intValue();
            partCountMap.put(head.getPartName(), new ArrayList<>());
        }
        if (minLsNo != maxLsNo) {
            map.put("lsNoStr", ZStringUtils.format("{}-{}", new Object[]{Integer.valueOf(minLsNo), Integer.valueOf(maxLsNo)}));
        } else {
            map.put("lsNoStr", ZStringUtils.format("{}", new Object[]{Integer.valueOf(minLsNo)}));
        }
        SdCompany companyInfo = cuttingDispatchHeadMapper.getCompanyById(UserIdThread.get().getCompanyId());
        map.put("company", companyInfo.getAbbrName());
        List<ManulDispatchDetail> detailList = cuttingDispatchHeadMapper.selectByDispatchDetailType(UserIdThread.get().getCompanyId(), dispatchType);
        List<Object> sizeNoList = new ArrayList();
        List<Object> cutSizeList = new ArrayList();
        if ("BF".equals(UserIdThread.get().getCompanyId())) {
            sizeNoList.add("订单号码");
            cutSizeList.add("冲刀号码");
        }
        if ("HF".equals(UserIdThread.get().getCompanyId())) {
            sizeNoList.add("Số lệnh");
            cutSizeList.add("Số đấm dao");
        }
        Map<String, Integer> partSizeMap = new HashMap<>();
        Map<String, Integer> part2CutNumMap = new HashMap<>();
        detailList.forEach(detail -> {
            if (!sizeNoList.contains(detail.getSizeNo())) {
                sizeNoList.add(detail.getSizeNo());
                cutSizeList.add(detail.getCutSize());
            }
            partSizeMap.put(ZStringUtils.format("{}-{}", new Object[]{detail.getPartName(), detail.getSizeNo()}), Integer.valueOf(detail.getQty().intValue()));
            part2CutNumMap.put(detail.getPartName(), detail.getCutNum());
        });
        sizeNoList.forEach(sizeNo -> {
            for (String partName : partCountMap.keySet()) {
                if ("订单号码".equals(sizeNo))
                    continue;
                if (ZStringUtils.isNotNull(partSizeMap.get(ZStringUtils.format("{}-{}", new Object[]{partName, sizeNo})))) {
                    ((List) partCountMap.get(partName)).add(partSizeMap.get(ZStringUtils.format("{}-{}", new Object[]{partName, sizeNo})));
                    continue;
                }
                ((List<Integer>) partCountMap.get(partName)).add(Integer.valueOf(0));
            }
        });
        sizeNoList.add("片数");
        sizeNoList.add("合计");
        cutSizeList.add("");
        cutSizeList.add("");
        List<List<Object>> partList = new ArrayList<>();
        partList.add(sizeNoList);
        partList.add(cutSizeList);
        partCountMap.keySet().forEach(partNameKey -> {
            List<Integer> countList = (List<Integer>) partCountMap.get(partNameKey);
            List<Object> record = new ArrayList();
            record.add(partNameKey);
            int total = 0;
            for (Integer qty : countList) {
                total += qty.intValue();
                record.add(qty);
            }
            record.add(part2CutNumMap.get(partNameKey));
            record.add(Integer.valueOf(total));
            partList.add(record);
        });
        map.put("partList", partList);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        return ResponseInfo.ok(map);
    }

    @Override
    public void updatePrintStatus(String dispatchNo) {
        cuttingDispatchHeadMapper.updatePrintStatus(UserIdThread.get().getCompanyId(), dispatchNo);
    }

    @Override
    public ResponseInfo returnLotNo(String searchKey) {
        List<Map<String, Object>> list = cuttingDispatchHeadMapper.returnLotNo(UserIdThread.get().getCompanyId(), searchKey);
        return ResponseInfo.ok(list);
    }

    @Override
    public ResponseInfo returnRoundAndPro(String lotNo) {
        LotHead lotHead = new LotHead();
        lotHead.setLotNo(lotNo);
        lotHead = cuttingDispatchHeadMapper.getLotHead(lotHead);
        if (ZStringUtils.isNull(lotHead)) {
            return ResponseInfo.error("指令信息不存在");
        }
        List<Map<String, Object>> list = cuttingDispatchHeadMapper.returnRoundAndPro(lotHead);
        List<Integer> lsNos = new ArrayList<>();
        List<String> process = new ArrayList<>();
        for (Map<String, Object> record : list) {
            if (!lsNos.contains(Integer.valueOf(record.get("lsNo").toString()))) {
                lsNos.add(Integer.valueOf(record.get("lsNo").toString()));
            }
            if (!process.contains(record.get("process").toString())) {
                process.add(record.get("process").toString());
            }
        }
        Map<String, Object> data = new HashMap<>();
        data.put("lsNo", lsNos);
        data.put("process", process);
        return ResponseInfo.ok(data);
    }

    @Autowired
    private CutPlanMapper mapper;

    @Override
    public ResponseInfo loadCutLabelTrees(String lotNo, List<String> lsNos, List<String> process) {
        LotHead lotHead = new LotHead();
        lotHead.setLotNo(lotNo);
        lotHead = cuttingDispatchHeadMapper.getLotHead(lotHead);
        if (ZStringUtils.isNull(lotHead)) {
            return ResponseInfo.error("获取手工派工轮次-指令信息不存在!");
        }
        if (ZStringUtils.isEmpty(lsNos) || ZStringUtils.isEmpty(process))
            return ResponseInfo.error("请先选择轮次和工艺");
        List<ManulDispatchTreeData> list = cuttingDispatchHeadMapper.selectUnfinishLsNo(lotHead, lsNos, process);
        List<ManulDispatchTreeData> results = new ArrayList();
        Map<String, ManulDispatchTreeData> partNameMap = new HashMap();
        Map<String, ManulDispatchTreeData> sizeNoMap = new HashMap();
        Iterator var8 = list.iterator();
        while (var8.hasNext()) {
            ManulDispatchTreeData mdtd = (ManulDispatchTreeData) var8.next();
            ManulDispatchTreeData partRecord = (ManulDispatchTreeData) partNameMap.get(mdtd.getPartName());
            if (ZStringUtils.isNull(partRecord)) {
                partRecord = new ManulDispatchTreeData();
                partRecord.setTitle(mdtd.getProcess() + mdtd.getPartName0());
                partRecord.setRemainQty(0);
                partRecord.setLeaf(false);
                partRecord.setType("part");
                partNameMap.put(mdtd.getPartName(), partRecord);
                results.add(partRecord);
            }
            String sizeNoKey = ZStringUtils.format("{}-{}", new Object[]{mdtd.getPartName(), mdtd.getSizeNo()});
            ManulDispatchTreeData sizeRecord = (ManulDispatchTreeData) sizeNoMap.get(sizeNoKey);
            if (ZStringUtils.isNull(sizeRecord)) {
                sizeRecord = new ManulDispatchTreeData();
                sizeRecord.setTitle(mdtd.getSizeNo());
                sizeRecord.setRemainQty(0);
                sizeRecord.setLeaf(false);
                sizeRecord.setType("size");
                sizeNoMap.put(sizeNoKey, sizeRecord);
                partRecord.getChildren().add(sizeRecord);
            }

            sizeRecord.getChildren().add(mdtd);
            sizeRecord.setRemainQty(sizeRecord.getRemainQty() + mdtd.getRemainQty());
            partRecord.setRemainQty(partRecord.getRemainQty() + mdtd.getRemainQty());
            mdtd.setTitle(mdtd.getLsNo().toString());
            mdtd.setType("label");
            mdtd.setLeaf(true);
        }
        return ResponseInfo.ok(results);
    }

    @Override
    public List<Map<String, Object>> loadManulWorkerList(Date dispatchDate, String searchKey) {
        List<Map<String, Object>> list = cuttingDispatchHeadMapper.loadManulWorkerList(UserIdThread.get().getCompanyId(), dispatchDate, searchKey);
        return list;
    }

    @Override
    @Transactional
    @RedisLock(key = "cutting:dispatchHead:insertIntoDispatch")
    public ResponseInfo insertIntoDispatch(List<ManulDispatchDetail> details, String lotNo, Date dispatchDate, String manulWorkerId) {
        LotHead lotHead = new LotHead();
        lotHead.setLotNo(lotNo);
        if (dispatchDate == null) {
            return ResponseInfo.error("派工日期不能为空");
        }
        lotHead = cuttingDispatchHeadMapper.getLotHead(lotHead);
        if (ZStringUtils.isNull(lotHead)) {
            return ResponseInfo.error("手工派工-指令信息不存在!");
        }
        Employee employee = null;
        employee = cuttingDispatchHeadMapper.selectByWorkerIdDisPatch(UserIdThread.get().getCompanyId(), manulWorkerId);
        if (ZStringUtils.isNull(employee)) {
            return ResponseInfo.error("手工派工-员工信息不存在!");
        }
        String planNo = doSgDispatch(lotHead, details, dispatchDate, employee, null);
        if (ZStringUtils.isNotBlank(planNo)) {
            return ResponseInfo.ok(planNo, "手工派工成功！");
        }
        return ResponseInfo.error("手工派工失败！！！");
    }

    @Override
    public ResponseInfo summaryPrintTotal(Date beginDate, Date endDate) {
        HashMap<String, Object> map = new HashMap<>();
        List<ManulDispatchHead> headList = cuttingDispatchHeadMapper.selectByDispatchDate(UserIdThread.get().getCompanyId(), beginDate, endDate);
        if (ZStringUtils.isEmpty(headList)) {
            return ResponseInfo.error("未找到派工信息");
        }
        Date now = new Date();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd");
        map.put("printDate", sdf1.format(now));
        map.put("dispatchDateDuring", ZStringUtils.format("{}-{}", new Object[]{sdf2.format(beginDate), sdf2.format(endDate)}));
        Map<String, List<ManulDispatchHead>> worker2HeadMap = new LinkedHashMap<>();
        for (ManulDispatchHead cdh : headList) {
            List<ManulDispatchHead> list = worker2HeadMap.get(cdh.getWorkerName());
            if (ZStringUtils.isNull(list)) {
                list = new ArrayList<>();
                worker2HeadMap.put(cdh.getWorkerName(), list);
            }
            list.add(cdh);
        }
        map.put("worker2HeadMap", worker2HeadMap);
        return ResponseInfo.ok(map);
    }

    @Autowired
    RedisService redisService;

    private String doSgDispatch(LotHead lotHead, List<ManulDispatchDetail> details, Date dispatchDate, Employee employee, String combineLotNo) {
        List<ManulDispatchHead> heads = new ArrayList();
        Map<String, ManulDispatchHead> headMap = new HashMap();
        Map<String, ManulDispatchDetail> sizeMap = new HashMap();
        ManulDispatchHead head1 = new ManulDispatchHead();
        head1.setLotNo(lotHead.getLotNo());
        head1.setCompanyId(lotHead.getCompanyId());
        List<ManulDispatchDetail> heads1 = cuttingDispatchHeadMapper.searchListOther(head1);
        List<PcCuttingLsDetail> lsDetails = mapper.getBatchNumberDetails(lotHead.getLotNo(), UserIdThread.get().getCompanyId());
        Set<String> set = lsDetails.stream().map(PcCuttingLsDetail::getSizeNo).collect(Collectors.toSet());
        List<ManulDispatchDetail> collect1 = details.stream().filter(x -> !set.contains(x.getSizeNo())).collect(Collectors.toList());
        if (ZStringUtils.isNotEmpty(collect1)) {
            throw new ServiceErrorException("该号码不存在，请重新派工");
        }
        for (ManulDispatchDetail detail : details) {
            detail.setLotNo(lotHead.getLotNo());
            detail.setCompanyId(UserIdThread.get().getCompanyId());
            int qty = 0;
            qty += detail.getQty();
            List<ManulDispatchDetail> collect = heads1.stream().filter(x -> x.getLotNo().equals(detail.getLotNo()) && x.getLsNo().equals(detail.getLsNo()) && x.getCompanyId().equals(detail.getCompanyId()) && x.getPartName().equals(detail.getPartName()) && x.getSizeNo().equals(detail.getSizeNo())).collect(Collectors.toList());
            for (ManulDispatchDetail manulDispatchDetail : collect) {
                qty += manulDispatchDetail.getQty();
            }
            List<PcCuttingLsDetail> collect2 = lsDetails.stream().filter(x -> x.getLotNo().equals(detail.getLotNo()) && x.getLsNo().equals(detail.getLsNo()) && x.getCompanyId().equals(detail.getCompanyId())&& x.getSizeNo().equals(detail.getSizeNo())).collect(Collectors.toList());
            if (qty>collect2.get(0).getQty()) throw new ServiceErrorException("派工数量不能大于指令数量");
        }
        String dispatchDept = sdCompanyMapper.getDispatchDept(UserIdThread.get().getCompanyId());
        Date now = new Date();
        ManulDispatchDetail mdd;
        ManulDispatchHead manulDispatchHead = null;
        for (Iterator var10 = details.iterator(); var10.hasNext(); manulDispatchHead.setDispatchQty(manulDispatchHead.getDispatchQty() + mdd.getQty().intValue())) {
            mdd = (ManulDispatchDetail) var10.next();
            String lotNo = mdd.getLotNo();
            String sizeKey = ZStringUtils.format("{}-{}-{}-{}", new Object[]{mdd.getPartName(), mdd.getLotNo(), mdd.getSizeNo(), mdd.getLsNo()});
            if (ZStringUtils.isNotNull(sizeMap.get(sizeKey))) {
                throw new ServiceErrorException("同一个派工单，不允许出现两条同工序部位、指令、同号码、同轮次的派工信息!");
            }
            sizeMap.put(sizeKey, mdd);
            mdd.setCompanyId(lotHead.getCompanyId());
            if (lotNo == null) {
                lotNo = lotHead.getLotNo();
                mdd.setLotNo(lotNo);
            }
            Integer sizeSeq = cuttingDispatchHeadMapper.selectSizeSeq(mdd);
            String partLotKey = ZStringUtils.format("{}-{}", new Object[]{mdd.getPartName(), mdd.getLotNo()});
            manulDispatchHead = (ManulDispatchHead) headMap.get(partLotKey);
            if (ZStringUtils.isNull(manulDispatchHead)) {
                manulDispatchHead = new ManulDispatchHead();
                manulDispatchHead.setCompanyId(lotHead.getCompanyId());
                manulDispatchHead.setDispatchDate(dispatchDate);
                manulDispatchHead.setDispatchDept(dispatchDept);
                manulDispatchHead.setDispatchName(UserIdThread.get().getUserName());
                manulDispatchHead.setDispatchQty(0);
                manulDispatchHead.setLotNo(lotNo);
                manulDispatchHead.setLsNo(Integer.MAX_VALUE);
                manulDispatchHead.setLsNo2(Integer.MIN_VALUE);
                manulDispatchHead.setPartName(mdd.getPartName());
                manulDispatchHead.setPartName0(mdd.getPartName0());
                manulDispatchHead.setProcess(mdd.getProcess());
                manulDispatchHead.setProcessCode(mdd.getProcessCode());
                manulDispatchHead.setSysDate(now);
                manulDispatchHead.setUserId(UserIdThread.get().getUserId());
                manulDispatchHead.setWorkerId(employee.getWorkerId());
                manulDispatchHead.setWorkerIdNo(employee.getIdNo());
                manulDispatchHead.setWorkerName(employee.getName());
                if (combineLotNo != null) {
                    manulDispatchHead.setCombineLotNo(combineLotNo);
                }

                headMap.put(partLotKey, manulDispatchHead);
                heads.add(manulDispatchHead);
            }
            mdd.setDispatchDate(dispatchDate);
            mdd.setLsNo2(mdd.getLsNo());
            mdd.setSeqNo(sizeSeq);
            mdd.setWorkerId(employee.getWorkerId());
            mdd.setWorkerIdNo(employee.getIdNo());
            mdd.setWorkerName(employee.getName());
            if (mdd.getLsNo() < manulDispatchHead.getLsNo()) {
                manulDispatchHead.setLsNo(mdd.getLsNo());
            }

            if (mdd.getLsNo() > manulDispatchHead.getLsNo2()) {
                manulDispatchHead.setLsNo2(mdd.getLsNo());
            }
        }

//        String nextDispatchType = redisService.barcodeCreatAdd("S", 10);
        String dept = null;
        if ("BF".equals(UserIdThread.get().getCompanyId())) {
            dept = "手工";
        } else if ("HF".equals(UserIdThread.get().getCompanyId())) {
            dept = "Thủ công";
        }
        Integer max = cuttingDispatchHeadMapper.selectMaxDispatchType(dept);
        if (max == null) max = 0;
        String nextDispatchType = "S" + String.format("%010d", ++max);
        heads.stream().forEach((head) -> {
            head.setDispatchType(nextDispatchType);
        });
        details.stream().forEach((detail) -> {
            detail.setDispatchType(nextDispatchType);
        });
        try {
            for (ManulDispatchHead head : heads) {
                List<ManulDispatchDetail> collect = details.stream().filter(x -> x.getLotNo().equals(head.getLotNo()) && x.getPartName().equals(head.getPartName())).collect(Collectors.toList());
                if (collect.isEmpty()) throw new ServiceErrorException("请勿重复派工！");
            }
            cuttingDispatchHeadMapper.batchInsert1(heads);
            cuttingDispatchHeadMapper.batchInsert2(details);
        } catch (Exception e) {
            RedisAtomicInteger ato = new RedisAtomicInteger("S", redisService.getConnectionFactory());
            ato.decrementAndGet();
            throw new ServiceErrorException(e.getMessage());
        }
        return nextDispatchType;
    }

    /**
     * 冲裁派工-查询轮次
     * <p>
     * 插入冲裁资料-查询轮次
     *
     * @param lotNo
     * @return
     */
    @Override
    public ResponseInfo loadLsNoByLotNo(String lotNo) {
        String companyId = UserInfoUtil.getUserInfo().getCompanyId();
        CutDispatchLotDto canDispatchLotNo = cuttingDispatchHeadMapper.getCanDispatchLotNo(companyId, lotNo);
        if (ObjectUtils.isEmpty(canDispatchLotNo)) {
            return ResponseInfo.ok();
        } else if ("Y".equals(canDispatchLotNo.getCombineLot())) {
            return ResponseInfo.ok(cuttingDispatchHeadMapper.selectUnDispatchLsNoByCombineLot(companyId, lotNo));
        } else {
            return ResponseInfo.ok(cuttingDispatchHeadMapper.selectUnDispatchLsNoByLotNo(companyId, lotNo));
        }
    }

    /**
     * 插入冲裁资料-查询号码
     *
     * @param lotNo
     * @param lsNos
     * @return
     */
    @Override
    public List<Map<String, String>> loadCombineDispatchSizeNo(String lotNo, List<String> lsNos) {
        String companyId = UserInfoUtil.getUserInfo().getCompanyId();
        CutDispatchLotDto canDispatchLotNo = cuttingDispatchHeadMapper.getCanDispatchLotNo(companyId, lotNo);
        if (ObjectUtils.isEmpty(canDispatchLotNo)) {
            throw new ServiceErrorException("无效的指令信息");
        } else if ("Y".equals(canDispatchLotNo.getCombineLot())) {
            return cuttingDispatchHeadMapper.selectUnDispatchCombineSizeNo(companyId, lotNo, lsNos);
        } else {
            return cuttingDispatchHeadMapper.selectUnDispatchSizeNo(companyId, lotNo, lsNos);
        }
    }

    /**
     * 当日冲工点检信息
     *
     * @param dispatchDate
     * @param cutWorkerName
     * @return
     */
    @Override
    public ResponseInfo loadCuttingCheckerList2(LocalDate dispatchDate, String cutWorkerName) {
        String companyId = UserInfoUtil.getUserInfo().getCompanyId();
        List<CuttingCheckerDto> cuttingCheckerList = cuttingDispatchHeadMapper.loadCuttingCheckerList2(companyId, dispatchDate, cutWorkerName);
        if (ObjectUtils.isEmpty(cuttingCheckerList)) {
            return ResponseInfo.ok();
        } else {
            Map<String, List<CuttingCheckerDto>> groupedByDeptName = cuttingCheckerList.stream()
                    .collect(Collectors.groupingBy(CuttingCheckerDto::getDeptName));
            return ResponseInfo.ok(groupedByDeptName);
        }
    }

    /**
     * 查看派工明细
     *
     * @param dispatchDate
     * @param workerId
     * @return
     */
    @Override
    public ResponseInfo cutWorkerDispatchHeadList(LocalDate dispatchDate, String workerId) {
        String companyId = UserInfoUtil.getUserInfo().getCompanyId();
        LambdaQueryWrapper<PcEmployee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PcEmployee::getWorkerId, workerId).
                eq(PcEmployee::getCompanyId, companyId);
        PcEmployee pcEmployee = pcEmployeeMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(pcEmployee)) {
            return ResponseInfo.error("未找到员工信息");
        }
        List<PcCuttingDispatchHeadDto> list = cuttingDispatchHeadMapper.getPcCuttingDispatchHeadList(companyId, dispatchDate, workerId);
        if (ObjectUtils.isEmpty(list)) {
            return ResponseInfo.ok();
        } else {
            Map<String, List<PcCuttingDispatchHeadDto>> listMap = list.stream()
                    .collect(Collectors.groupingBy(PcCuttingDispatchHeadDto::getPlanNo));
            return ResponseInfo.ok(listMap);
        }
    }

    /**
     * 插入派工资料-插入
     *
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo doDispatch(doDispatchRequest request) {
        if (ObjectUtils.isEmpty(request.getDispatchDate())) {
            return ResponseInfo.error("请选择派工日期!");
        }
        if (ObjectUtils.isEmpty(request.getLabelNos())) {
            return ResponseInfo.error("请选择号码!");
        }
        if (ObjectUtils.isEmpty(request.getCutWorkerId())) {
            return ResponseInfo.error("请选择冲工!");
        }
        String companyId = UserInfoUtil.getUserInfo().getCompanyId();
        CutDispatchLotDto canDispatchLotNo = cuttingDispatchHeadMapper.getCanDispatchLotNo(companyId, request.getLotNo());
        if (ObjectUtils.isEmpty(canDispatchLotNo)) {
            throw new ServiceErrorException("无效的指令信息，无法派工!");
        } else {
            CuttingCheckerDto cuttingWorkerRelation = cuttingDispatchHeadMapper.selectCutWorkerRelation(companyId, request.getCutWorkerId());
            if (ObjectUtils.isEmpty(cuttingWorkerRelation)) {
                throw new ServiceErrorException("未找到冲工人员资料信息,请核实!");
            } else {
                String checkWorkName = null;
                String checkIdNo = null;
                if (!ObjectUtils.isEmpty(request.getCheckWorkerId())) {
                    LambdaQueryWrapper<PcEmployee> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(PcEmployee::getWorkerId, request.getCheckWorkerId())
                            .eq(PcEmployee::getCompanyId, companyId);
                    PcEmployee checkWorker = pcEmployeeMapper.selectOne(wrapper);
                    if (!ObjectUtils.isEmpty(checkWorker)) {
                        checkWorkName = checkWorker.getName();
                        checkIdNo = checkWorker.getIdNo();
                    }
                }
                List<PcCuttingLsLabel> totalList = cuttingDispatchHeadMapper.selectUnDispatchByLabelNos(request.getLabelNos(), companyId);
                if (totalList.size() != request.getLabelNos().size()) {
                    throw new ServiceErrorException("标签信息不完整,或者存在已被派工的标签,请核实！");
                } else {
                    boolean combineDispatch = false;
                    if (!request.getLotNo().equals(((PcCuttingLsLabel) totalList.get(0)).getLotNo())) {
                        combineDispatch = true;
                    }

                    PcLotHead firstLotHead = new PcLotHead();
                    LambdaQueryWrapper<PcLotHead> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(PcLotHead::getLotNo, request.getLotNo())
                            .eq(PcLotHead::getCompanyId, companyId);
                    firstLotHead = pcLotHeadMapper.selectOne(wrapper);
                    Integer maxPlanNo = this.cuttingDispatchHeadMapper.selectPlanNoMax();
                    String planNo = String.format("%010d", maxPlanNo);
                    Map<String, Map<String, Integer>> part2SizeNo2QtyMap = new HashMap();
                    Map<String, Map<String, List<PcCuttingLsLabel>>> part2SizeNo2LabelsMap = new HashMap();
                    Set<String> subLotNoSet = new HashSet();
                    Map<String, List<PcCuttingLsLabel>> lotNo2LabelMap = new HashMap();
                    Iterator var20 = totalList.iterator();
                    // 新增一个 map 存储每个部位的总数
                    Map<String, Integer> part2TotalQtyMap = new HashMap<>();

                    while (var20.hasNext()) {
                        PcCuttingLsLabel crl = (PcCuttingLsLabel) var20.next();
                        List<PcCuttingLsLabel> subLotLabelList = (List) lotNo2LabelMap.get(crl.getLotNo());
                        if (ObjectUtils.isEmpty(subLotLabelList)) {
                            subLotLabelList = new ArrayList();
                            lotNo2LabelMap.put(crl.getLotNo(), subLotLabelList);
                        }

                        Map<String, Integer> sizeNo2QtyMap = (Map) part2SizeNo2QtyMap.get(crl.getPartName());
                        Map<String, List<PcCuttingLsLabel>> sizeNo2LabelsMap = (Map) part2SizeNo2LabelsMap.get(crl.getPartName());
                        if (ObjectUtils.isEmpty(sizeNo2QtyMap)) {
                            sizeNo2QtyMap = new HashMap();
                            part2SizeNo2QtyMap.put(crl.getPartName(), sizeNo2QtyMap);
                            sizeNo2LabelsMap = new HashMap();
                            part2SizeNo2LabelsMap.put(crl.getPartName(), sizeNo2LabelsMap);
                        }

                        Integer qty = (Integer) ((Map) sizeNo2QtyMap).get(crl.getSizeNo());
                        List<PcCuttingLsLabel> labels = (List) ((Map) sizeNo2LabelsMap).get(crl.getSizeNo());
                        if (ObjectUtils.isEmpty(qty)) {
                            qty = 0;
                            labels = new ArrayList();
                            ((Map) sizeNo2LabelsMap).put(crl.getSizeNo(), labels);
                        }

                        qty = qty + crl.getQty();
                        ((Map) sizeNo2QtyMap).put(crl.getSizeNo(), qty);
                        // 新增的部位总数累加逻辑
                        part2TotalQtyMap.put(crl.getPartName(),
                                part2TotalQtyMap.getOrDefault(crl.getPartName(), 0) + crl.getQty());
                        ((List) labels).add(crl);
                        ((List) subLotLabelList).add(crl);
                        subLotNoSet.add(crl.getLotNo());
                    }

                    if (part2SizeNo2QtyMap.size() > 1) {
                        String str = null;
                        Iterator var49 = part2SizeNo2QtyMap.values().iterator();

                        while (var49.hasNext()) {
                            Map<String, Integer> size2QtyMap = (Map) var49.next();
                            List<String> qtyStrList = new ArrayList();
                            Iterator var59 = size2QtyMap.keySet().iterator();

                            while (var59.hasNext()) {
                                String sizeNoKey = (String) var59.next();
                                String key = "{" + sizeNoKey + "}-" + "{" + size2QtyMap.get(sizeNoKey) + "}";
                                qtyStrList.add(key);
                            }

                            String result = (String) qtyStrList.stream().sorted().collect(Collectors.joining(","));
                            if (ObjectUtils.isEmpty(str)) {
                                str = result;
                            } else if (!str.equals(result)) {
                                throw new ServiceErrorException("多个部位合并派工的号码数量必须一致");
                            }
                        }
                    }

                    List<PcCuttingLsDetail> lsDetails = mapper.getBatchNumberDetails(firstLotHead.getLotNo(), companyId);
                    //订单总数量（号码 → 数量），这里转成总和
                    int orderTotalQty = lsDetails.stream()
                            .mapToInt(PcCuttingLsDetail::getQty)
                            .sum();

                    List<CuttingDispatchHead> heads = cuttingDispatchHeadMapper.searchDispatchDeadCountList(companyId, request.getLotNo());
                    Map<String, Integer> part2QtyMap = heads.stream()
                            .collect(Collectors.toMap(
                                    CuttingDispatchHead::getPartName,
                                    CuttingDispatchHead::getDispatchQty
                            ));
                    // 本次派单数量（部位 → 总数）
                    for (Map.Entry<String, Integer> entry : part2TotalQtyMap.entrySet()) {
                        String partName = entry.getKey();
                        int dispatchQty = entry.getValue();
                        int alreadyQty = part2QtyMap.getOrDefault(partName, 0);
                        if (dispatchQty + alreadyQty > orderTotalQty) {
                            throw new ServiceErrorException(
                                    String.format("部位【%s】派单数量超出订单总数 (订单数量:%d, 已派数量:%d, 本次数量:%d)",
                                            partName, orderTotalQty, alreadyQty, dispatchQty)
                            );
                        }
                    }


                    var20 = lotNo2LabelMap.keySet().iterator();
                    int totalQty;
                    int qty;
                    while (var20.hasNext()) {
                        String subLotNo = (String) var20.next();
                        List<PcCuttingLsLabel> list = (List) lotNo2LabelMap.get(subLotNo);
                        Map<String, PcLotDetailDto> lotSizeNoMap = new LinkedHashMap();
                        List<PcLotDetailDto> lotDetailList = pcLotHeadMapper.getCodeDetails(subLotNo, companyId);
                        if (ObjectUtils.isEmpty(lotDetailList)) {
                            throw new ServiceErrorException("指令号码信息不存在,请核实!");
                        }
                        lotDetailList.stream().forEach((ld) -> {
                            PcLotDetailDto var10000 = (PcLotDetailDto) lotSizeNoMap.put(ld.getSizeNo(), ld);
                        });
                        Map<String, List<PcCuttingLsLabel>> partLabelMap = new LinkedHashMap();

                        PcCuttingLsLabel crl;
                        Object subList;
                        for (Iterator var27 = list.iterator(); var27.hasNext(); ((List) subList).add(crl)) {
                            crl = (PcCuttingLsLabel) var27.next();
                            subList = (List) partLabelMap.get(crl.getPartName());
                            if (ObjectUtils.isEmpty(subList)) {
                                subList = new ArrayList();
                                partLabelMap.put(crl.getPartName(), (List) subList);
                            }
                        }

                        List<CuttingDispatchHead> headList = new ArrayList();
                        List<CuttingDispatchDetail> detailList = new ArrayList();
                        Date now = new Date();
                        Iterator var30 = partLabelMap.keySet().iterator();

                        while (var30.hasNext()) {
                            String partName = (String) var30.next();
                            CuttingDispatchHead cuttingDispatchHead = new CuttingDispatchHead();
                            totalQty = 0;
                            cuttingDispatchHead.setCompanyId(companyId);
                            cuttingDispatchHead.setDeptNo(cuttingWorkerRelation.getDeptNo());
                            cuttingDispatchHead.setDispatchDate(request.getDispatchDate());
                            PcCuttingLsLabel firstRecord = (PcCuttingLsLabel) ((List) partLabelMap.get(partName)).get(0);
                            qty = 1;
                            int maxLsNo = 1;
                            cuttingDispatchHead.setLotNo(firstRecord.getLotNo());
                            cuttingDispatchHead.setPartName(partName);
                            cuttingDispatchHead.setWorkerId(cuttingWorkerRelation.getCutWorkerId());
                            cuttingDispatchHead.setWorkerIdNo(cuttingWorkerRelation.getIdNo());
                            cuttingDispatchHead.setWorkerName(cuttingWorkerRelation.getCutWorkerName());
                            cuttingDispatchHead.setCheckerIdNo(checkIdNo);
                            cuttingDispatchHead.setCheckerName(checkWorkName);
                            cuttingDispatchHead.setUserId(UserIdThread.get().getLoginName());
                            cuttingDispatchHead.setSysDate(now);
                            cuttingDispatchHead.setDispatchDept(cuttingWorkerRelation.getDeptName());
                            cuttingDispatchHead.setDispatchName(UserIdThread.get().getLoginName());
                            cuttingDispatchHead.setDispatchCnName(UserIdThread.get().getUserName());
                            cuttingDispatchHead.setPlanNo(planNo);
                            cuttingDispatchHead.setOutDept(cuttingWorkerRelation.isOutDept());
                            if (combineDispatch) {
                                cuttingDispatchHead.setCombineLotNo(request.getLotNo());
                            }

                            Map<String, List<PcCuttingLsLabel>> sizeLabelMap = new LinkedHashMap();

                            Iterator var38;
                            Object sizeList;
                            for (var38 = ((List) partLabelMap.get(partName)).iterator(); var38.hasNext(); ((List) sizeList).add(crl)) {
                                crl = (PcCuttingLsLabel) var38.next();
                                totalQty += crl.getQty();
                                if (qty > crl.getLsNo()) {
                                    qty = crl.getLsNo();
                                }

                                if (maxLsNo < crl.getLsNo()) {
                                    maxLsNo = crl.getLsNo();
                                }

                                sizeList = (List) sizeLabelMap.get(crl.getSizeNo());
                                if (ObjectUtils.isEmpty(sizeList)) {
                                    sizeList = new ArrayList();
                                    sizeLabelMap.put(crl.getSizeNo(), (List<PcCuttingLsLabel>) sizeList);
                                }
                            }

                            var38 = sizeLabelMap.keySet().iterator();

                            while (var38.hasNext()) {
                                String sizeNoKey = (String) var38.next();
                                int sizeMinLsNo = 1;
                                int sizeMaxLsNo = 1;
                                int sizeTotalQty = 0;
                                CuttingDispatchDetail cuttingDispatchDetail = new CuttingDispatchDetail();
                                PcCuttingLsLabel sizeFirstRecord = (PcCuttingLsLabel) ((List) sizeLabelMap.get(sizeNoKey)).get(0);
                                cuttingDispatchDetail.setDispatchDate(request.getDispatchDate());
                                cuttingDispatchDetail.setCompanyId(companyId);
                                cuttingDispatchDetail.setLotNo(sizeFirstRecord.getLotNo());
                                cuttingDispatchDetail.setPartName(partName);
                                cuttingDispatchDetail.setSeqNo(Integer.valueOf(((PcLotDetailDto) lotSizeNoMap.get(sizeNoKey)).getSeqNo()));
                                cuttingDispatchDetail.setSizeNo(sizeNoKey);
                                cuttingDispatchDetail.setWorkerId(cuttingWorkerRelation.getCutWorkerId());
                                cuttingDispatchDetail.setWorkerIdNo(cuttingWorkerRelation.getIdNo());
                                cuttingDispatchDetail.setWorkerName(cuttingWorkerRelation.getCutWorkerName());
                                cuttingDispatchDetail.setPlanNo(planNo);
                                cuttingDispatchDetail.setOutDept(cuttingWorkerRelation.isOutDept());
                                if (combineDispatch) {
                                    cuttingDispatchDetail.setCombineLotNo(request.getLotNo());
                                }

                                for (Iterator var45 = ((List) sizeLabelMap.get(sizeNoKey)).iterator(); var45.hasNext(); sizeTotalQty += crl.getQty()) {
                                    crl = (PcCuttingLsLabel) var45.next();
                                    if (sizeMinLsNo > crl.getLsNo()) {
                                        sizeMinLsNo = crl.getLsNo();
                                    }

                                    if (sizeMaxLsNo < crl.getLsNo()) {
                                        sizeMaxLsNo = crl.getLsNo();
                                    }
                                }

                                cuttingDispatchDetail.setLsNo(sizeMinLsNo);
                                cuttingDispatchDetail.setLsNo2(sizeMaxLsNo);
                                cuttingDispatchDetail.setQty(sizeTotalQty);
                                detailList.add(cuttingDispatchDetail);
                            }

                            cuttingDispatchHead.setLsNo(qty);
                            cuttingDispatchHead.setLsNo2(maxLsNo);
                            cuttingDispatchHead.setDispatchQty(totalQty);
                            headList.add(cuttingDispatchHead);
                        }
                        cuttingDispatchHeadMapper.addPcCuttingDispatchHeadList(headList);
                        cuttingDispatchHeadMapper.addPcCuttingDispatchDetailList(detailList);
                    }

                    Date now = new Date();
                    int total = 0;
                    if (combineDispatch) {
                        LotPartCombineInfo lotPartCombineInfo = new LotPartCombineInfo();
                        lotPartCombineInfo.setCompanyId(companyId);
                        lotPartCombineInfo.setLotNo(request.getLotNo());
                        List<LotPartCombineInfo> combineParts = cuttingDispatchHeadMapper.selectByLotNo(lotPartCombineInfo);
                        Set<String> combinePartSet = new HashSet();
                        combineParts.stream().forEach((combinePart) -> {
                            combinePartSet.add(combinePart.getPartName());
                        });
                        int defaultBagQty = 200;
                        Iterator var67 = part2SizeNo2LabelsMap.keySet().iterator();

                        label166:
                        while (true) {
                            while (true) {
                                if (!var67.hasNext()) {
                                    break label166;
                                }

                                String partName = (String) var67.next();
                                Map<String, List<PcCuttingLsLabel>> size2LabelsMap = (Map) part2SizeNo2LabelsMap.get(partName);
                                if (combinePartSet.contains(partName)) {
                                    List<String> tempRowids = new ArrayList();
                                    size2LabelsMap.values().forEach((crls) -> {
                                        crls.forEach((crl) -> {
                                            tempRowids.add(crl.getLabelNo());
                                        });
                                    });
                                    total += cuttingDispatchHeadMapper.updateDispatchNo(companyId, tempRowids, planNo, cuttingWorkerRelation.getCutWorkerName(), cuttingWorkerRelation.getCutWorkerId(), cuttingWorkerRelation.getDeptNo(), cuttingWorkerRelation.getDeptName());
                                } else {
                                    int bagQty = defaultBagQty;
                                    Integer configMaxBagQty = cuttingDispatchHeadMapper.getMaxConfigBagQty(companyId, subLotNoSet, partName);
                                    if (ObjectUtils.isEmpty(configMaxBagQty) && configMaxBagQty > 0) {
                                        bagQty = configMaxBagQty;
                                    }

                                    ArrayList tempRowids;
                                    for (Iterator var76 = size2LabelsMap.keySet().iterator(); var76.hasNext(); total += cuttingDispatchHeadMapper.updateCombineDispatchNo(companyId, tempRowids, planNo, cuttingWorkerRelation.getCutWorkerName(), cuttingWorkerRelation.getCutWorkerId(), cuttingWorkerRelation.getDeptNo(), cuttingWorkerRelation.getDeptName(), request.getLotNo())) {
                                        String sizeNo = (String) var76.next();
                                        totalQty = 0;
                                        tempRowids = new ArrayList();
                                        Iterator var79 = ((List) size2LabelsMap.get(sizeNo)).iterator();

                                        while (var79.hasNext()) {
                                            PcCuttingLsLabel crl = (PcCuttingLsLabel) var79.next();
                                            totalQty += crl.getQty();
                                            tempRowids.add(crl.getLabelNo());
                                        }

                                        while (totalQty > 0) {
                                            qty = bagQty;
                                            if (bagQty > totalQty) {
                                                qty = totalQty;
                                            }

                                            totalQty -= qty;
                                            if (totalQty <= 50) {
                                                qty += totalQty;
                                                totalQty = 0;
                                            }

                                            String uuid = UUID.randomUUID().toString().toUpperCase();
                                            LotLabelCombineInfo combineLabel = new LotLabelCombineInfo();
                                            combineLabel.setUuid(uuid);
                                            combineLabel.setCompanyId(companyId);
                                            combineLabel.setLotNo(request.getLotNo());
                                            combineLabel.setCreateDate(now);
                                            combineLabel.setCreateUserId(UserIdThread.get().getLoginName());
                                            combineLabel.setCreateUserName(UserIdThread.get().getUserName());
                                            combineLabel.setDispatchNo(planNo);
                                            combineLabel.setDispatchWorker(cuttingWorkerRelation.getCutWorkerName());
                                            combineLabel.setDispatchWorkerId(cuttingWorkerRelation.getCutWorkerId());
                                            combineLabel.setDispatchDeptNo(cuttingWorkerRelation.getDeptNo());
                                            combineLabel.setDispatchDeptName(cuttingWorkerRelation.getDeptName());
                                            combineLabel.setLsNo(1);
                                            combineLabel.setPartName(partName);
                                            combineLabel.setQty(qty);
                                            combineLabel.setSizeNo(sizeNo);
                                            combineLabel.setStyle(firstLotHead.getStyle());
                                            combineLabel.setStyleColor(firstLotHead.getColor());
                                            cuttingDispatchHeadMapper.addLotLabelCombineInfo(combineLabel);
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        total = this.cuttingDispatchHeadMapper.updateDispatchNo(companyId, request.getLabelNos(), planNo, cuttingWorkerRelation.getCutWorkerName(), cuttingWorkerRelation.getCutWorkerId(), cuttingWorkerRelation.getDeptNo(), cuttingWorkerRelation.getDeptName());
                    }
                    if (total != request.getLabelNos().size()) {
                        throw new ServiceErrorException("更新派工标签异常，存在已被派工的标签");
                    } else {
                        return ResponseInfo.ok(planNo);
                    }
                }
            }
        }
    }

    /**
     * 冲裁派工删除
     *
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo deleteByDispatchNo(List<deleteRequest> request) {
        if (ObjectUtils.isEmpty(request)) {
            return ResponseInfo.error("请选择记录!");
        }
        String companyId = UserIdThread.get().getCompanyId();
        List<CuttingDispatchHead> list = cuttingDispatchHeadMapper.getCuttingDispatchHeadByRequest(companyId, request);

        if (list.size() != request.size()) {
            throw new ServiceErrorException("存在无效的派工信息");
        } else {
            long time = new Date().getTime();
            Iterator var4 = list.iterator();

            while (var4.hasNext()) {
                CuttingDispatchHead head = (CuttingDispatchHead) var4.next();
                if (!"冯长春".equals(UserIdThread.get().getUserName()) && time - head.getDispatchDate().getTime() > 60 * 60 * 24 * 1000L) {
                    return ResponseInfo.error("隔天记录,不能删除!");
                }
            }

            int result = 0;
            CuttingDispatchHead head;
            for (Iterator var11 = list.iterator(); var11.hasNext(); result += cuttingDispatchHeadMapper.deleteByPartNamePlanNo(head)) {
                head = (CuttingDispatchHead) var11.next();
                List<DispatchCollection> dc = cuttingDispatchHeadMapper.queryByDispatchNo(head.getPlanNo());
                if (dc != null && dc.size() > 0) {
                    throw new ServiceErrorException("派工单已采集,不能删除!");
                }

                int salaryList = this.cuttingDispatchHeadMapper.queryByDispatchNoAndPartName(head);
                if (salaryList > 0) {
                    throw new ServiceErrorException("派工单已结算,不能删除!");
                }

                int hasCollectLabelCount = cuttingDispatchHeadMapper.countHasCollectLabel(companyId, head.getPlanNo(), head.getPartName());
                if (hasCollectLabelCount > 0) {
                    throw new ServiceErrorException("派工单【" + head.getPlanNo() + "】部位【" + head.getPartName() + "】已扫描入库,无法删除派工!");
                }
                cuttingDispatchHeadMapper.clearDispatchInfo(head);
                cuttingDispatchHeadMapper.deleteByDispatchHead(head);
                if (!ObjectUtils.isEmpty(head.getCombineLotNo())) {
                    cuttingDispatchHeadMapper.deleteByPartNameDispatchNo(head);
                }
            }
            return ResponseInfo.ok(result);
        }
    }

    /**
     * 冲裁派工汇总打印
     *
     * @param beginDate
     * @param endDate
     * @return
     */
    @Override
    public ResponseInfo summaryPrint(LocalDate beginDate, LocalDate endDate) {
        Map<String, Object> map = new HashMap();
        List<CuttingDispatchHead> headList = this.cuttingDispatchHeadMapper.selectByDispatchDate2(UserIdThread.get().getCompanyId(), UserIdThread.get().getLoginName(), beginDate, endDate);
        if (ObjectUtils.isEmpty(headList)) {
            return ResponseInfo.error("未找到派工信息");
        }
        Date now = new Date();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd");
        map.put("printDate", sdf1.format(now));
        map.put("dispatchDateDuring", ZStringUtils.format("{}-{}", beginDate.format(formatter), endDate.format(formatter)));
        Map<String, List<CuttingDispatchHead>> worker2HeadMap = new LinkedHashMap<>();
        for (CuttingDispatchHead cdh : headList) {
            List<CuttingDispatchHead> list = worker2HeadMap.get(cdh.getWorkerName());
            if (ObjectUtils.isEmpty(list)) {
                list = new ArrayList<>();
                worker2HeadMap.put(cdh.getWorkerName(), list);
            }
            list.add(cdh);
        }
        map.put("worker2HeadMap", worker2HeadMap);
        return ResponseInfo.ok(map);
    }

    /**
     * 打印轮次标签(按搜索条件)
     *
     * @param request
     * @return
     */
    @Override
    public ResponseInfo printLabel(dispatchHeadRequest request) {
        Map<String, Object> map = new HashMap();
        UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
        LambdaQueryWrapper<SdCompany> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SdCompany::getCompanyId, userInfo.getCompanyId());
        SdCompany sdCompany = sdCompanyMapper.selectOne(wrapper);
        map.put("company", sdCompany.getAbbrName());
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd");
        map.put("now", sdf.format(new Date()));
        request.setCompanyId(userInfo.getCompanyId());
        if (!ObjectUtils.isEmpty(request.getUserId())) {
            request.setUserId(userInfo.getLoginName());
        }

        List<CuttingRoundLabel> list = searchRoundLabel(request);
        for (CuttingRoundLabel crl : list) {
            if (!ObjectUtils.isEmpty(crl.getProcess())) {
                crl.setProcessList(Arrays.asList(crl.getProcess().split("/")));
            }
        }
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    private List<CuttingRoundLabel> searchRoundLabel(dispatchHeadRequest request) {
        List<String> planNos = cuttingDispatchHeadMapper.searchPlanNo(request);
        if (ObjectUtils.isEmpty(planNos)) {
            return new ArrayList();
        } else {
            cuttingDispatchHeadMapper.updatePrintLableFlag(request.getCompanyId(), planNos);
            return cuttingDispatchHeadMapper.selectByPlanNos(request.getCompanyId(), planNos);
        }
    }

    /**
     * 打印轮次标签-未打印
     *
     * @return
     */
    @Override
    public ResponseInfo UnPrintLabel() {
        Map<String, Object> map = new HashMap();
        UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
        LambdaQueryWrapper<SdCompany> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SdCompany::getCompanyId, userInfo.getCompanyId());
        SdCompany sdCompany = sdCompanyMapper.selectOne(wrapper);
        map.put("company", sdCompany.getAbbrName());
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd");
        map.put("now", sdf.format(new Date()));
        List<CuttingRoundLabel> list = selectUnPrintRoundLabel();
        for (CuttingRoundLabel crl : list) {
            if (!ObjectUtils.isEmpty(crl.getProcess())) {
                crl.setProcessList(Arrays.asList(crl.getProcess().split("/")));
            }
        }
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    private List<CuttingRoundLabel> selectUnPrintRoundLabel() {
        UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
        List<String> planNos = cuttingDispatchHeadMapper.selectUnPrintLabel(userInfo.getCompanyId(), userInfo.getLoginName());
        if (ObjectUtils.isEmpty(planNos)) {
            return new ArrayList();
        } else {
            cuttingDispatchHeadMapper.updatePrintLableFlag(userInfo.getCompanyId(), planNos);
            return cuttingDispatchHeadMapper.selectByPlanNos(userInfo.getCompanyId(), planNos);
        }
    }

    /**
     * 打印派工单
     *
     * @param planNo
     * @return
     */
    @Override
    public ResponseInfo planNoCombinePrint(String planNo) {
        UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
        List<CuttingDispatchHead> headList = cuttingDispatchHeadMapper.selectByPlanNo(userInfo.getCompanyId(), planNo);
        if (ObjectUtils.isEmpty(headList)) {
            return ResponseInfo.error("未找到派工信息!");
        }
        CuttingDispatchHead firstRecord = headList.get(0);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> map = new HashMap();
        map.put("planNo", planNo);
        map.put("printDate", sdf1.format(new Date()));
        map.put("dispatchDate", sdf1.format(firstRecord.getDispatchDate()));
        map.put("cutWorkerName", firstRecord.getWorkerName());
        map.put("checkWorkerName", ZStringUtils.isNull(firstRecord.getCheckerName()) ? "自检" : firstRecord.getCheckerName());
        LambdaQueryWrapper<PcLotHead> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PcLotHead::getLotNo, firstRecord.getLotNo()).
                eq(PcLotHead::getCompanyId, userInfo.getCompanyId());
        PcLotHead pcLotHead = pcLotHeadMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(pcLotHead)) {
            return ResponseInfo.error("指令不存在!");
        }
        List<String> lotNoList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(pcLotHead.getOrderQty()) && pcLotHead.getSurplusQty().intValue() > 0) {
            map.put("orderQtyStr", ZStringUtils.format("{}+{}", new Object[]{pcLotHead.getOrderQty().intValue(), pcLotHead.getSurplusQty().intValue()}));
            lotNoList.add(ZStringUtils.format("{}+{}", new Object[]{pcLotHead.getOrderQty().intValue(), pcLotHead.getSurplusQty().intValue()}));
        } else {
            map.put("orderQtyStr", pcLotHead.getSurplusQty().intValue());
            lotNoList.add(ZStringUtils.format("{}", new Object[]{pcLotHead.getSurplusQty().intValue()}));
        }
        int minLsNo = Integer.MAX_VALUE;
        int maxLsNo = Integer.MIN_VALUE;
        for (CuttingDispatchHead head : headList) {
            if (minLsNo > head.getLsNo().intValue()) minLsNo = head.getLsNo().intValue();
            if (maxLsNo < head.getLsNo2().intValue()) maxLsNo = head.getLsNo2().intValue();
        }
        if (minLsNo != maxLsNo) {
            map.put("lsNoStr", ZStringUtils.format("{}-{}", new Object[]{Integer.valueOf(minLsNo), Integer.valueOf(maxLsNo)}));
        } else {
            map.put("lsNoStr", ZStringUtils.format("{}", new Object[]{Integer.valueOf(minLsNo)}));
        }
        map.put("color", pcLotHead.getColor());
        map.put("style", pcLotHead.getStyle());
        map.put("cutNo", pcLotHead.getCutNo());
        map.put("lastNo", pcLotHead.getLastNo());
        map.put("lotNo", pcLotHead.getLotNo());
        LambdaQueryWrapper<SdCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SdCompany::getCompanyId, userInfo.getCompanyId());
        SdCompany sdCompany = sdCompanyMapper.selectOne(queryWrapper);
        map.put("company", sdCompany.getAbbrName());
        Integer cutNumCount = headList.stream()
                .filter(head -> head.getCutNum() != null)
                .mapToInt(CuttingDispatchHead::getCutNum)
                .sum();
        map.put("cutNumCount", cutNumCount);
        map.put("list", headList);
        List<String> sizeNoList = new ArrayList<>();
        sizeNoList.add("订单数");
        sizeNoList.add("订单号码");
        List<String> cutNoList = new ArrayList<>();
        cutNoList.add("--");
        cutNoList.add("冲刀号");
        lotNoList.add(pcLotHead.getLotNo());
        List<String> countList = new ArrayList<>();
        countList.add("");
        countList.add("合计");
        List<CuttingDispatchDetail> detailList = cuttingDispatchHeadMapper.selectPdfByPlanNo(planNo);
        List<Integer> qtyList = new ArrayList<>();
        detailList.forEach(detail -> {
            if (!sizeNoList.contains(detail.getSizeNo())) {
                sizeNoList.add(detail.getSizeNo());
                cutNoList.add(detail.getCutSize());
                lotNoList.add(String.valueOf(detail.getQty()));
                qtyList.add(detail.getQty());
                countList.add(String.valueOf(detail.getQty()));
            }
        });
        Integer sum = qtyList.stream()
                .mapToInt(Integer::intValue)
                .sum();
        sizeNoList.add("合计");
        lotNoList.add(String.valueOf(sum));
        countList.add(String.valueOf(sum));
        List<Object> sizeList = new ArrayList<>();
        sizeList.add(sizeNoList);
        sizeList.add(cutNoList);
        sizeList.add(lotNoList);
        sizeList.add(countList);
        map.put("sizeList", sizeList);
        cuttingDispatchHeadMapper.updatePrintFlag(userInfo.getCompanyId(), planNo);
        return ResponseInfo.ok(map);
    }

    /**
     * 打印标签
     *
     * @param planNo
     * @return
     */
    @Override
    public ResponseInfo printCombineLabel(String planNo) {
        UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
        List<CuttingDispatchHead> headList = cuttingDispatchHeadMapper.selectByPlanNo(userInfo.getCompanyId(), planNo);
        if (ObjectUtils.isEmpty(headList)) {
            return ResponseInfo.error("无效的派工单!");
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat("MM/dd");
        Map<String, Object> map = new HashMap();
        map.put("now", sdf1.format(new Date()));
        LambdaQueryWrapper<SdCompany> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SdCompany::getCompanyId, userInfo.getCompanyId());
        SdCompany sdCompany = sdCompanyMapper.selectOne(wrapper);
        map.put("company", sdCompany.getAbbrName());
        List<CuttingRoundLabel> list = searchCombineRoundLabel(planNo, userInfo.getCompanyId());
        for (CuttingRoundLabel crl : list) {
            if (!ObjectUtils.isEmpty(crl.getProcess())) {
                crl.setProcessList(Arrays.asList(crl.getProcess().split("/")));
            }
        }
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    private List<CuttingRoundLabel> searchCombineRoundLabel(String planNo, String companyId) {
        List<String> planNos = new ArrayList();
        planNos.add(planNo);
        List<CuttingRoundLabel> list = cuttingDispatchHeadMapper.selectByPlanNos(companyId, planNos);
        cuttingDispatchHeadMapper.updatePrintLableFlag(companyId, planNos);
        return list;
    }
}
